package com.sport.common.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Author: Huang jw
 * Mail:1182175529@qq.com
 * Date:2018/10/17.
 * Time:15:33.
 * Describe: 七牛云配置
 */
public class QiniuUtil {
    private final static String ACCESSKEY;      //AccessKey的值
    private final static String SECRETKEY;      //SecretKey的值
    private final static String BUCKET;         //空间名
    private final static String DOMAIN;         //访问域名
    private final static long EXPIRE;           //超时时间
    private final static Configuration CONFIG;

    public static String getDOMAIN() {
        return DOMAIN;
    }

    static {
        PropertyUtil propertyUtil = new PropertyUtil("config/qiniu.properties");
        ACCESSKEY = propertyUtil.getProperty("QINIU_AK");
        SECRETKEY = propertyUtil.getProperty("QINIU_SK");
        BUCKET = propertyUtil.getProperty("QINIU_BUCKET");
        DOMAIN = propertyUtil.getProperty("QINIU_DOMAIN");
        EXPIRE = Long.parseLong(propertyUtil.getProperty("QINIU_EXPIRE"));
        CONFIG = new Configuration(Zone.zone2());       //设置为华南服务器
    }

    /**
     * 获取认证
     *
     * @return 认证
     */
    private static Auth getAuth() {
        return Auth.create(ACCESSKEY, SECRETKEY);
    }

    private static String getVistURrl(String key) {
        StringBuilder builder = new StringBuilder();
        builder.append(DOMAIN);
        builder.append(key);
        return builder.toString();
    }

    /**
     * 获得会话
     *
     * @return
     */
    private static String getToken(String key, boolean override) {
        Auth auth = getAuth();
        StringBuilder token = new StringBuilder();
        if (override) {
            return token.append(auth.uploadToken(BUCKET, key)).toString();
        }
        return token.append(auth.uploadToken(BUCKET)).toString();
    }

    /**
     * 上传本地文件
     *
     * @param key      文件名
     * @param filePath 文件路径
     * @return 七牛云保存的key
     */
    public static String uploadFile(String key, String filePath) {
        return uploadFile(key, filePath, false);
    }

    /**
     * 上传本地文件
     *
     * @param key      文件名
     * @param filePath 文件路径
     * @param override 是否选择覆盖
     * @return 七牛云保存的key
     */
    public static String uploadFile(String key, String filePath, boolean override) {
        UploadManager uploadManager = new UploadManager(CONFIG);
        try {
            Response response = uploadManager.put(filePath, key, getToken(key, override));
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return getVistURrl(putRet.key);
        } catch (QiniuException e) {
            Response r = e.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return null;
    }

    /**
     * 上传文件
     *
     * @param file 上传文件
     * @param key  文件名
     * @return 文件访问路径
     */
    public static String uploadMultipartFile(MultipartFile file, String key, boolean override) {

        try {
            byte[] uploadBytes = multipartFileToBytes(file);         //把文件转化为字节数组
            UploadManager manager = new UploadManager(CONFIG);
            String token = getToken(key, override);
            Response response = manager.put(uploadBytes, key, token);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); //默认上传接口回复对象
            System.out.println(putRet.key);//key 文件名
            System.out.println(putRet.hash);//hash 七牛返回的文件存储的地址，可以使用这个地址加七牛给你提供的前缀访问到这个视频。
            return getVistURrl(putRet.key);
        } catch (Exception e) {
            System.err.println("七牛云上传图片失败");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 不覆盖上传
     *
     * @param file 上传文件
     * @param key  文件名
     * @return 文件访问路径
     */
    public static String uploadMultipartFile(MultipartFile file, String key) {
        return uploadMultipartFile(file, key, false);
    }

    /**
     * 上传多张图片
     *
     * @param files
     * @param key
     * @param override
     * @return
     */
    public static String[] uploadMulFiles(MultipartFile[] files, String[] key, boolean override) {
        String[] savePath = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            savePath[i] = uploadMultipartFile(files[i], key[i], override);
        }
        return savePath;
    }

    /**
     * 不覆盖上传多个文件
     *
     * @param files 文件数组
     * @param key   文件名
     * @return
     */
    public static String[] uploadMulFiles(MultipartFile[] files, String[] key) {
        return uploadMulFiles(files, key, false);
    }

    /**
     * MultipartFile转字节数组
     *
     * @param file 目标文件
     * @return 字节数组
     */
    private static byte[] multipartFileToBytes(MultipartFile file) {
        try {
            System.out.println("过来了0");
            InputStream in = file.getInputStream();
            System.out.println("过来了1");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ;
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = in.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            System.err.println("MultipartFile转化字节数组异常");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取文件访问地址
     *
     * @param fileName 文件云端存储的名称
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String fileUrl(String fileName) throws UnsupportedEncodingException {
        String encodedFileName = URLEncoder.encode(fileName, "utf-8");
        String publicUrl = String.format("%s/%s", DOMAIN, encodedFileName);
        Auth auth = getAuth();
        long expireInSeconds = EXPIRE;
        if (-1 == expireInSeconds) {
            return auth.privateDownloadUrl(publicUrl);
        }
        return auth.privateDownloadUrl(publicUrl, expireInSeconds);
    }

    /**
     * 用多个字符串组成目录，最后一个参数作为文件名
     * @param directory
     */
    public static String getNewName(String... directory) {
        StringBuilder builder = new StringBuilder();
    //    builder.append(FileConstant.BASH_NAME);
        for (String s : directory) {
            builder.append("/");
            builder.append(s);
        }
        return builder.toString();
    }
    /**
     * 获取原文件的文件后缀名
     * @param file 原文件
     */
    public static String getSuffix(MultipartFile file ){
        System.out.println("获取原文件的文件后缀名");
        String oldName = file.getOriginalFilename();
        return oldName.substring(oldName.indexOf("."));             //获取点后缀名
    }

    /**
     * 客户端获取上传凭证，1代表覆盖上传，0代表普通上传
     * @param uploadType 上传的类型
     * @param key  文件的名字
     * @return
     */
    public static String getUpToken(Integer uploadType,String key){
        Auth auth = Auth.create(ACCESSKEY,SECRETKEY);
        if(uploadType==0){
            return auth.uploadToken(BUCKET);
        }else {
            return auth.uploadToken(BUCKET,key);
        }
    }


}
